import axios, { type AxiosInstance } from 'axios';
import {ElMessage} from "element-plus";
import router from "@/router";
// 创建 axios 实例并配置基础设置
const axiosInstance: AxiosInstance = axios.create({
  baseURL: 'http://localhost:8080/api', // 基础 URL
  timeout: 5000, // 超时时间设置
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
axiosInstance.interceptors.request.use(
  (config) => {
    // 在发送请求之前做一些处理，例如加入 token
    const token = localStorage.getItem('token'); // 假设 token 存储在 localStorage
    if (token) {
      config.headers['token'] = `${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    // 如果响应的code大于900，说明token发生了问题，直接让用户重新登录
    if (response.data.code > 900) {
      ElMessage.error({
        message:response.data.msg
    })
    router.push('/');
    }
    return response;
  },  // 可以统一处理返回数据
  (error) => {
    // 这里可以统一处理错误
    console.error('API Request Error:', error);
    return Promise.reject(error);
  }
);

const baseService = {
  // 封装 GET 请求
  doGet: function <T>(url: string, params?: object): Promise<T> {
    return axiosInstance.get<T>(url, { params })
      .then((response) => response.data)
      .catch((error) => {
        console.error('GET Request Error:', error);
        throw error;  // 抛出错误，供外部捕获
      });
  },

  // 封装 POST 请求
  doPost: function <T>(url: string, data?: object): Promise<T> {
    return axiosInstance.post<T>(url, data)
      .then((response) => response.data)
      .catch((error) => {
        console.error('POST Request Error:', error);
        throw error;
      });
  },

  // 封装 PUT 请求
  doPut: function <T>(url: string, data?: object): Promise<T> {
    return axiosInstance.put<T>(url, data)
      .then((response) => response.data)
      .catch((error) => {
        console.error('PUT Request Error:', error);
        throw error;
      });
  },

  // 封装 DELETE 请求
  doDelete: function <T>(url: string,params?:object): Promise<T> {
    return axiosInstance.delete<T>(url, { params })
      .then((response) => response.data)
      .catch((error) => {
        console.error('DELETE Request Error:', error);
        throw error;
      });
  },
};

export { baseService };
